<template>
  <view class="app-container">
    <image class="background" src="/static/images/background.jpg" mode="aspectFill"></image>

    <view class="bar-box" :style="{ marginTop: titleMargin + 'px' }">
      <image class="back" src="/static/images/back.png" @click="back"></image>
      <view class="title">个人主页</view>
    </view>

    <view class="info">
      <image class="avatar" mode="aspectFill" @click="previewImg(info.avatar_path)" :src="info.avatar_path ? info.avatar_path : '/static/images/default_avatar.png'"></image>
      <view class="name-box">
        <view class="name">{{ info.nickname }}</view>
        <image v-if="info.rz_status == 1" class="icon" src="/static/images/name_icon.png"></image>
        <view @click="follow" :class="['follow-box', info.is_follow == 1 ? 'cancel' : '']" v-if="info.is_follow > -1">
          <block v-if="info.is_follow == 0">
            <image class="icon" src="/static/images/add.png"></image>
            <view class="text">关注</view>
          </block>
          <block v-else>
            <image class="icon" src="/static/images/true.png"></image>
            <view class="text">取消关注</view>
          </block>
        </view>
      </view>
      <view class="id">ID：{{ info.id_num }}</view>
    </view>

    <view class="main-box">
      <view class="follow-box">
        <view class="tab-box">
          <view class="text">关注我的</view>
          <view class="count">（{{ info.follow_me_count }}）</view>
        </view>
        <view class="tab-box">
          <view class="text">我关注的</view>
          <view class="count">（{{ info.me_follow_count }}）</view>
        </view>
      </view>

      <scroll-view scroll-y enable-flex class="scroll">
        <view class="info-box">
          <view class="set-box">
            <view class="xx">基本信息</view>
          </view>
          <view class="row">
            <view class="text">性别：{{ info.gender }}</view>
            <view class="text">年份：{{ info.birth_year }}</view>
          </view>
          <view class="row">
            <view class="text">居住：{{ info.residence }}</view>
            <view class="text">户籍：{{ info.hukou }}</view>
          </view>
          <view class="row">
            <view class="text">身高：{{ info.height ? info.height + 'cm' : '' }}</view>
            <view class="text">体重：{{ info.weight ? info.weight + 'kg' : '' }}</view>
          </view>
          <view class="row">
            <view class="text">职业：{{ info.occupation }}</view>
            <view class="text">体型：{{ info.body_type }}</view>
          </view>
        </view>
        <view class="info-box">
          <view class="set-box">
            <view class="xx">详细信息</view>
          </view>
          <view class="row">
            <view class="text">婚况：{{ info.marital_status }}</view>
            <view class="text">学历：{{ info.education_level }}</view>
          </view>
          <view class="row">
            <view class="text">公司：{{ info.company_type }}</view>
            <view class="text">年收入：{{ info.annual_income }}</view>
          </view>
          <view class="row">
            <view class="text">住房：{{ info.housing_status }}</view>
            <view class="text">车辆：{{ info.car_status }}</view>
          </view>
        </view>
        <view class="info-box">
          <view class="set-box">
            <view class="xx">择偶要求</view>
          </view>
          <view class="row">
            <view class="text">年龄：{{ info.requirement_age }}</view>
            <view class="text">身高：{{ info.requirement_height }}</view>
          </view>
          <view class="row">
            <view class="text">体型要求：{{ info.requirement_body_type }}</view>
            <view class="text">婚姻状况：{{ info.requirement_marital_status }}</view>
          </view>
          <view class="row">
            <view class="text">学历要求：{{ info.requirement_education_level }}</view>
            <view class="text">年收入：{{ info.requirement_annual_income }}</view>
          </view>
          <view class="row">
            <view class="text">居住地：{{ info.requirement_residence }}</view>
            <view class="text">小孩要求：{{ info.requirement_has_children }}</view>
          </view>
          <view class="row">
            <view class="text">购房：{{ info.requirement_buying_status }}</view>
            <view class="text">购车：{{ info.requirement_car_status }}</view>
          </view>
        </view>

        <view class="btn-box">
          <view class="btn xc" @click="openPhotosModal">查看相册</view>
          <view class="btn lx" @click="openContactModal">联系方式</view>
        </view>
      </scroll-view>
    </view>

    <!-- 相册弹框 START -->
    <view v-if="photosModal" class="modal-overlay" @click="closePhotosModal">
      <view class="modal" @click.stop>
        <view class="modal-content">
          <image class="close" src="/static/images/close.png" @click="closePhotosModal"></image>
          <scroll-view scroll-y enable-flex class="photos-box">
            <view class="show-box" v-for="(item, index) in info.photos_arr" :key="index">
              <image class="photo" @click="previewImgs(info.photos_arr, index)" mode="aspectFill" :src="item.path"></image>
            </view>
          </scroll-view>
        </view>
      </view>
    </view>
    <!-- 相册弹框 END -->

    <!-- 联系方式弹框 START -->
    <view v-if="contactModal" class="modal-overlay" @click="closeContactModal">
      <view class="modal" @click.stop>
        <view class="modal-content">
          <image class="close" src="/static/images/close.png" @click="closeContactModal"></image>
          <view class="modal-title">联系方式</view>
          <view class="row-box">
            <view class="row">
              <view class="text">微信</view>
              <view class="input" style="width: 60%;height: 34rpx;">{{ info.wechat }}</view>
            </view>
            <view class="row">
              <view class="text">QQ</view>
              <view class="input" style="width: 60%;height: 34rpx;">{{ info.qq }}</view>
            </view>
            <view class="row">
              <view class="text">手机</view>
              <view class="input" style="width: 60%;height: 34rpx;">{{ info.mobile }}</view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- 联系方式弹框 END -->

    <!-- 登录弹框 START -->
    <view id="mask" v-if="show_login" @click.stop>
      <view class="mask-content" @click.stop>
        <form @submit="formSubmit" class="main-content">
          <view class="title">完善资料</view>
          <button open-type="chooseAvatar" @chooseavatar="getAvatar" class="avatar-btn">
            <image class="btnImg" :src="avatar_path" mode="aspectFill"></image>
          </button>
          <input type="text" :value="avatar" name="avatar" style="display: none">

          <view class="row">
            <view class="left">昵称</view>
            <input type="nickname" @focus="this.showLoginModel = true" @input="this.showLoginModel = true" :value="username" name="nickname" class="input" placeholder="请输入昵称">
          </view>

          <view class="row" style="border-top: none">
            <view class="left">手机号</view>
            <button open-type="getPhoneNumber" :plain="true" @getphonenumber="getPhoneNumber" class="mobile-btn" v-if="!mobile">获取手机号</button>
            <block v-else>
              <input type="number" :value="mobile" name="mobile" style="display: none">
              <view class="input">{{mobile}}</view>
            </block>
          </view>

          <view class="agree-box">
            <button hover-class="none" class="item agree-btn" open-type="agreePrivacyAuthorization">
              <checkbox :checked="is_agree" @click="doAgree" class="checkbox round color" color="#32A4FF" style="background: #FFF"/>
            </button>

            <view class="box">
              阅读并接受
              <text class="text" @click="openPrivacy">{{ privacyContractName }}</text>
            </view>
          </view>

          <input type="text" :value="openid" name="openid" style="display: none">

          <view class="btn-box">
            <button :plain="true" class="button cancel" @click="this.show_login = false">取消</button>
            <button form-type="submit" class="button save">保存</button>
          </view>
        </form>
      </view>
    </view>
    <!-- 登录弹框 END -->

    <!-- 相册、联系方式无权查看弹框 START -->
    <view v-if="authModal" class="modal-overlay" @click="closeAuthModal">
      <view class="modal" @click.stop>
        <view class="modal-content">
          <image class="close" src="/static/images/close.png" @click="closeAuthModal"></image>
          <scroll-view scroll-y enable-flex class="photos-box" style="margin-top: 80rpx;max-height: calc(70vh - 80rpx);">
            <rich-text space="nbsp" :nodes="authArticle"></rich-text>
          </scroll-view>
        </view>
      </view>
    </view>
    <!-- 相册、联系方式无权查看弹框 END -->

  </view>
</template>

<script>
import http from '@/utils/http'

export default {
  data() {
    return {
      swiperIndex: 0, // 当前轮播图索引
      title: '',
      titleMargin: 0, // 动态顶部间距
      info: {},
      photosModal: false,
      contactModal: false,
      authModal: false,
      readyOpenModal: '',// 准备打开的弹框；photosModal:相册弹框；contactModal:联系方式弹框
      authArticle: '',
      show_login: false,
      login_to_url: '',// 登录之后跳转的页面
      privacyContractName: '《喜来啦隐私保护指引》',
      is_agree: false,
      avatar: 0,
      avatar_path: '../../static/images/default_avatar.png',
      mobile: '',
    };
  },

  created() {
    this.setDynamicMargin()
  },

  onLoad: function (options) {
    var follow_user_id = options.user_id ? options.user_id : 0;
    var user_id = uni.getStorageSync('user_id') ? uni.getStorageSync('user_id') : 0;
    this.$http.post('/index/Api/userInfo', {user_id, follow_user_id}).then(res => {
      if (res.data.result == 1) {
        this.info = res.data.data;
      } else {
        this.$common.doErrorResult(res);
      }
    })

    this.$http.post('/index/Api/getAuthArticle', {type: 1}).then(res => {
      this.authArticle = res.data.data;
    })
  },

  methods: {
    setDynamicMargin() {
      const windowInfo = uni.getWindowInfo();
      this.titleMargin = windowInfo.statusBarHeight + 10; // 直接使用状态栏高度
    },

    back: function () {
      uni.navigateBack();
    },

    openPhotosModal: function () {
      var user_id = uni.getStorageSync('user_id'),
        rz_status = uni.getStorageSync('rz_status');

      if (!user_id) {
        uni.showLoading({
          title: '自动登录中...',
          mask: true
        })

        uni.login({
          success: result => {
            var code = result.code;

            this.$http.post('/index/Api/openidToUserid', {code}).then(res => {
              uni.hideLoading();
              if (res.data.result === 1) {
                var user_id = res.data.data;
                uni.setStorageSync('user_id', user_id)
                var scene_user_id = uni.getStorageSync('scene_user_id') ? uni.getStorageSync('scene_user_id') : 0;

                this.readyOpenModal = 'photosModal';

                this.userCenter(user_id, scene_user_id);
              } else {
                this.show_login = true;
              }
            })
          }
        })
      } else {
        if (rz_status == 1) {
          this.photosModal = true;
        } else {
          this.authModal = true;
        }
      }
    },
    closePhotosModal: function () {
      this.readyOpenModal = '';
      this.photosModal = false;
    },

    openContactModal: function () {
      var user_id = uni.getStorageSync('user_id'),
        rz_status = uni.getStorageSync('rz_status');

      if (!user_id) {
        uni.showLoading({
          title: '自动登录中...',
          mask: true
        })

        uni.login({
          success: result => {
            var code = result.code;

            this.$http.post('/index/Api/openidToUserid', {code}).then(res => {
              uni.hideLoading();
              if (res.data.result === 1) {
                var user_id = res.data.data;
                uni.setStorageSync('user_id', user_id)
                var scene_user_id = uni.getStorageSync('scene_user_id') ? uni.getStorageSync('scene_user_id') : 0;

                this.readyOpenModal = 'contactModal';

                this.userCenter(user_id, scene_user_id);
              } else {
                this.show_login = true;
              }
            })
          }
        })
      } else {
        if (rz_status == 1) {
          this.contactModal = true;
        } else {
          this.authModal = true;
        }
      }
    },
    closeContactModal: function () {
      this.readyOpenModal = '';
      this.contactModal = false;
    },

    closeAuthModal: function () {
      this.authModal = false;
    },

    follow: function () {
      var content = this.info.is_follow == 1 ? '确定要取消关注吗？' : '确定要关注吗？',
        user_id = uni.getStorageSync('user_id') ? uni.getStorageSync('user_id') : 0,
        follow_user_id = this.info.user_id;

      uni.showModal({
        title: '操作提示',
        content: content,
        success: result => {
          if (result.confirm) {
            this.$http.post('/index/Api/follow', {user_id, follow_user_id}).then(res => {
              if (res.data.result == 1) {
                uni.showToast({
                  title: res.data.msg
                })

                if (this.info.is_follow == 1) {
                  // 取消关注
                  var new_is_follow = 0;
                  var follow_me_count = this.info.follow_me_count - 1 > 0 ? this.info.follow_me_count - 1 : 0;
                } else {
                  // 关注
                  var new_is_follow = 1;
                  var follow_me_count = this.info.follow_me_count + 1;
                }
                this.info.is_follow = new_is_follow;
                this.info.follow_me_count = follow_me_count;
              } else {
                this.$common.doErrorResult(res);
              }
            })
          }
        }
      })
    },

    previewImgs: function (imgs, index, path = 'path') {
      this.$common.previewImgs(imgs, index, path)
    },

    previewImg: function (img) {
      this.$common.previewImg(img)
    },

    openPrivacy: function () {
      uni.openPrivacyContract()
    },

    getAvatar: function (e) {
      var {avatarUrl} = e.detail;

      uni.uploadFile({
        url: http.config.baseURL + '/Upload/UploadFile/uniUploadPicture', //服务端图片上传接口地址
        filePath: avatarUrl,
        name: 'download',
        formData: {},
        success: res => {
          res = JSON.parse(res.data)
          if (res.result === 1) {
            uni.showToast({
              title: '上传头像成功'
            })
            this.showLoginModel = true;
            this.avatar_path = res.data.path;
            this.avatar = res.data.id;
          } else {
            uni.showToast({
              title: res.msg,
              icon: 'none'
            })
          }
        },
        fail: err => {
          setTimeout(() => {
            uni.hideLoading();
            uni.showToast({
              title: '图片上传失败',
              icon: 'none'
            })
          }, 500)
        }
      })
    },

    doAgree: function () {
      this.is_agree = !this.is_agree;
    },

    getPhoneNumber: function (e){
      var code = e.detail.code;
      this.$http.post('/index/Api/getMobile', {code}).then(res => {
        if (res.data.result === 1) {
          this.mobile = res.data.data
        }else{
          this.$common.doErrorResult(res)
        }
      })
    },

    formSubmit: function (e) {
      var formData = e.detail.value,
        timestamp = Date.parse(new Date()),//该值除以1000就是当前的时间戳,
        sync_timestamp = uni.getStorageSync('timestamp') ? uni.getStorageSync('timestamp') : 0,//获取时间戳缓存,
        now_timestamp = timestamp / 1000,
        long_time = now_timestamp - sync_timestamp;//距离上次点击按钮经过的时长（秒）,

      if (!this.is_agree) {
        uni.showToast({
          title: '请阅读并勾选小程序隐私保护指引',
          icon: 'none'
        })
        return;
      }

      uni.showLoading({
        title: '保存中...',
        mask: true
      })

      if (long_time > 3) {
        //将当前时间戳存为缓存
        uni.setStorageSync('timestamp', timestamp / 1000);

        uni.login({
          success: result => {
            var code = result.code;

            this.$http.post('/index/Api/getOpenid', {code}).then(res => {
              if (res.data.result === 1) {
                formData.openid = res.data.data;

                this.$http.post('/Index/Api/login', formData).then(res => {
                  uni.removeStorageSync('timestamp');
                  uni.hideLoading();

                  if (res.data.result === 1) {
                    var user_id = res.data.data;
                    uni.setStorageSync('user_id', user_id)

                    this.show_login = false;

                    var scene_user_id = uni.getStorageSync('scene_user_id') ? uni.getStorageSync('scene_user_id') : 0;
                    this.userCenter(user_id, scene_user_id)
                  } else {
                    this.$common.doErrorResult(res);
                  }
                })
              } else {
                this.$common.doErrorResult(res);
              }
            })
          }
        })
      }
    },

    userCenter: function (user_id, scene_user_id = 0) {
      this.$http.post('/index/Api/userCenter', {user_id, scene_user_id}).then(res => {
        if (res.data.result === 1) {
          var info = res.data.data,
            rz_status = info.rz_status;

          // 存储认证状态
          uni.setStorageSync('rz_status', rz_status)

          if (res.data.data.up_user_id > 0) uni.removeStorageSync('scene_user_id');

          if (rz_status == 0) {
            this.authModal = true;
          } else {
            if (this.readyOpenModal = 'photosModal') {
              this.photosModal = true;
            } else if (this.readyOpenModal = 'contactModal') {
              this.contactModal = true;
            }
          }
        } else {
          this.$common.doErrorResult(res);
        }
      })
    },

  },
}
</script>

<style lang="scss">
.app-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0 10rpx;

  button{
    border: none;
    padding: 0;
    margin: 0;
  }

  .info {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 10rpx;

    .avatar {
      width: 180rpx;
      height: 180rpx;
      border-radius: 50%;
    }

    .name-box {
      display: flex;
      margin-top: 20rpx;
      align-items: center;

      .name {
        font-size: 40rpx;
      }

      .icon {
        width: 26rpx;
        height: 26rpx;
        margin-left: 10rpx;
      }

      .follow-box {
        display: flex;
        align-items: center;
        padding: 6rpx 10rpx 6rpx 0;
        background-color: rgba(234, 86, 55, 0.8);
        border-radius: 40rpx;
        margin-left: 10rpx;

        .icon {
          width: 30rpx;
          height: 30rpx;
        }

        .text {
          font-size: 32rpx;
          color: #fff;
          margin-left: 8rpx;
        }
      }

      .cancel {
        background-color: #c9c5c5 !important;

        .text {
          color: #636161 !important;
        }
      }
    }

    .id {
      font-size: 32rpx;
    }
  }

  .main-box {
    display: flex;
    align-items: center;
    flex-direction: column;
    width: 100%;
    height: 70vh;
    border-radius: 40rpx 40rpx 0 0;
    background: linear-gradient(to bottom, rgba(228, 67, 35, 0.8), rgba(216, 216, 216, 0.2));
    overflow: hidden;
    position: absolute;
    bottom: 0;

    .follow-box {
      display: flex;
      justify-content: space-between;
      width: 70%;
      padding-top: 40rpx;

      .tab-box {
        flex: 1;
        text-align: center;
        font-size: 40rpx;
        color: #fff;

        .count {
          margin-top: 10rpx;
        }
      }
    }

    .scroll {
      display: flex;
      width: 100%;
      align-items: center;
      flex-direction: column;
      height: 60vh;

      .info-box {
        padding: 20rpx 30rpx;
        width: 82%;
        background: #fff;
        border-radius: 20rpx;
        margin-top: 20rpx;

        .xx {
          font-size: 40rpx;
          color: #F30E0E;
        }

        .row {
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-size: 32rpx;
          margin-top: 15rpx;

          .text {
            width: 50%;
            white-space: nowrap; /* 不换行 */
            overflow: hidden; /* 超出隐藏 */
            text-overflow: ellipsis; /* 省略号 */
            flex-shrink: 0; // 防止被挤压
          }
        }
      }

      .btn-box {
        display: flex;
        margin-top: 20rpx;
        width: 90%;
        justify-content: space-around;

        .btn {
          text-align: center;
          font-size: 36rpx;
          font-weight: bold;
          padding: 10rpx 30rpx;
          border-radius: 50rpx;
          width: 200rpx;
        }

        .xc{
          background-color: #F30E0E;
          color: #fff;
        }
        .lx{
          background-color: #EDC80F;
        }
      }
    }
  }

  .modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;

    .modal {
      width: 80%;

      .modal-content {
        position: relative;
        background: #fff;
        padding: 20rpx;
        border-radius: 20rpx;
        max-height: 70vh;

        .close {
          position: absolute;
          width: 40rpx;
          height: 40rpx;
          border-radius: 50%;
          right: 20rpx;
          top: 20rpx;
        }

        .modal-title {
          position: absolute;
          font-size: 40rpx;
          color: #F30E0E;
          top: 60rpx;
          left: 20rpx;
        }

        .row-box {
          margin-top: 100rpx;

          .row {
            display: flex;
            width: 100%;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30rpx;
            font-size: 32rpx;

            &:last-child {
              margin-bottom: 0;
            }

            .input {
              margin-left: 100rpx;
              padding: 10rpx 20rpx;
              border: 2rpx solid #dad6d6;
              border-radius: 20rpx;
            }

            .sex-box {
              flex: 1;
              margin-left: 100rpx;
              display: flex;
              justify-content: space-between;
              align-items: center;

              .sex {
                flex: 1;
                padding: 10rpx 0;
                border: 2rpx solid #dad6d6;
                border-radius: 20rpx;
                margin-right: 20rpx;
                text-align: center;

                &:last-child {
                  margin-right: 0;
                }
              }

              .active {
                border: 2rpx solid #F30E0E;
              }

            }

            .res-box {
              display: flex;

              .res {
                flex: 1;
                margin-right: 20rpx;
                text-align: right;
              }

              .icon {
                width: 20rpx;
                height: 28rpx;
              }
            }
          }
        }

        .photos-box {
          display: flex;
          flex-wrap: wrap;
          justify-content: space-between;
          width: 100%;
          margin-top: 130rpx;
          max-height: calc(70vh - 130rpx);

          .show-box {
            position: relative;
            width: 48%;
            margin-bottom: 10rpx;

            &:nth-last-child(1),
            &:nth-last-child(2) {
              margin-bottom: 0;
            }

            .photo {
              width: 100%;
              height: 260rpx;
            }
          }
        }
      }
    }
  }

}
</style>
